<?php
App::uses('FormAuthenticate', 'Controller/Component/Auth');

/**
 * An authentication adapter for AuthComponent.  Provides the ability to authenticate using POST
 * data.  Can be used by configuring AuthComponent to use it via the AuthComponent::$authenticate setting.
 *
 *
 * When configuring FormAuthenticate you can pass in settings to which fields, model and additional conditions
 * are used. See FormAuthenticate::$settings for more information.
 *
 */
class JingbeeAuthenticate extends FormAuthenticate {

	public $settings = array(		
		'types'  => array(
					'Admin'=>array(
							'fields' => array(
									'username' => 'username',
									'password' => 'password'
							),
							'userModel' => 'User',
							'scope' => array(),
							'recursive' => 0
					),
                    'FontEnd' => array(
							'fields' => array(
									'username' => 'username',
									'password' => 'password'
							),
							'userModel' => 'User',
							'scope' => array(),
							'recursive' => 0
					)
			),
			
			'fields' => array(
					'username' => 'username',
					'password' => 'password'
			),
			'userModel' => 'User',
			'scope' => array(),
			'recursive' => 0
	);
	
/**
 * Authenticates the identity contained in a request.  Will use the `settings.userModel`, and `settings.fields`
 * to find POST data that is used to find a matching record in the `settings.userModel`.  Will return false if
 * there is no post data, either username or password is missing, of if the scope conditions have not been met.
 *
 * @param CakeRequest $request The request that contains login information.
 * @param CakeResponse $response Unused response object.
 * @return mixed.  False on login failure.  An array of User data on success.
 */
	public function authenticate(CakeRequest $request, CakeResponse $response) {
		if(isset($request->data['type'])){
			$type = $request->data['type'];
			if( ! isset($this->settings['types'][$type]) ) 
                throw new Exception(__('Type %s login not setting',$type));
			$types = $this->settings['types'];
            
			$this->settings = array_merge(array('types'=>$types),$types[$type]);
		}
		
		// if not set model in from then reset to request
		$fields = $this->settings['fields'];
		$model = $this->settings['userModel'];
		
		if (empty($request->data[$model])) {
			$request->data[$model] = array(
					$fields['username'] => isset($request->data[$fields['username']])? $request->data[$fields['username']] : null,
					$fields['password'] => isset($request->data[$fields['password']])? $request->data[$fields['password']] : null
			);
		}
		$user = parent::authenticate($request, $response);  
		if(! empty($user) && is_array($user) && ! isset($user['group_id']) && isset($this->settings['groupId'])) {
			$user['group_id'] = $this->settings['groupId'];
		}
		
		return $user;
	}

}
